//////////////////////////////////////////////////////////////////////////
// FileName:Login
// CreateBy:DragonXiong
// CreateDate:2009-5-4
// Description:
//		Class Login,Used to Control Login
//      
// Modify Log:090531:Modify Session To Session Box.--Dragon
//            090623:Add Function AddLoginLog(),AddUserToApp(),JudgeUserExists().--Mark
//            090626:Add Function InitPage,judge action.--Mark
// Copyright:ASL-MIS
/////////////////////////////////////////////////////////////////////////
using System;
using System.Text;
using System.Web;
using System.Collections.Generic;

using Auto.Data.Security;
using Auto.Web.Common;
using Auto.Data.Setting;

namespace BaseSystem
{
    public partial class Login : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
            }

            

           
        }
        private void InitPage()
        {
            
            if (Request.QueryString["Action"] != null)
            {
                string action = Request.QueryString["Action"].ToString();
                if (action.Equals("Login", StringComparison.OrdinalIgnoreCase))
                {
                    if (JudgeOnline())
                    {
                        Response.Redirect("Main.aspx");
                    }
                }
                else
                {
                    Session.Abandon();
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {

            try
            {
                Users user = new Users(UserID.Text, PassWord.Text);
                if (user.Pause)
                {
                    lblMsg.Text = "The user is stop using!";
                    return;
                }
                else
                {
                    Session["UserID"] = UserID.Text;
                    SessionBox.User = user;

                    JudgeUserExists();
                    AddLoginLog();
                    AddUserToApp();
                    Response.Redirect("Main.aspx");
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
            }

        }

        /// <summary>
        /// Add Login Info to the database.
        /// </summary>
        private void AddLoginLog()
        {
            try
            {
                LoginLog loginlog = new LoginLog();
                loginlog.UserID = SessionBox.User.UserID;
                loginlog.LoginTime = DateTime.Now;
                loginlog.LogoutTime = null;
                loginlog.UserPCIP = Request.UserHostAddress;
                loginlog.UserPCName = GetHostNameByIp(Request.UserHostAddress);
                loginlog.Online = true;
                loginlog.LogoutType = string.Empty;
                loginlog.Insert();

                Session["currentloginid"] = loginlog.RecID;

            }
            catch (Exception ex)
            {
                Response.Redirect("Error.aspx?Msg=" + ex.Message);
            }
        }

        /// <summary>
        /// Get the name of user PC by user IP.
        /// </summary>
        /// <param name="ip">User IP</param>
        /// <returns>User PC Name</returns>
        public string GetHostNameByIp(string ip)
        {
            ip = ip.Trim();
            if (ip == string.Empty)
            {
                return string.Empty;
            }
            try
            {
                if (this.Ping(ip))
                {
                    System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(ip);
                    return host.HostName;
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Judge Ping 
        /// </summary>
        /// <param name="ip">User IP</param>
        /// <returns>Ping or not</returns>
        public bool Ping(string ip)
        {
            System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
            options.DontFragment = true;
            string data = "Test Data!";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 1000;
            System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
            if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Add "UserID" "SessionID" to the "GLOBAL_USER_LIST" list of Application.
        /// </summary>
        protected void AddUserToApp()
        {
            string userid = SessionBox.User.UserID;
            IDictionary<string, string> list = Application.Get("GLOBAL_USER_LIST") as IDictionary<string, string>;
            if (list == null)
            {
                list = new Dictionary<string, string>();
            }
            list.Remove(userid);
            list.Add(userid, Session.SessionID);
            Application.Lock();
            Application["GLOBAL_USER_LIST"] = list;
            Application.UnLock();
        }


        /// <summary>
        /// Judge the user exists in the "GLOBAL_USER_LIST" list of Application or not.
        /// If already exists,redirect to "ForceLogout.aspx".
        /// </summary>
        private void JudgeUserExists()
        {
            string userid = SessionBox.User.UserID;
            string sessionid = Session.SessionID;
            bool judgeexist = false;

            IDictionary<string, string> list = Application.Get("GLOBAL_USER_LIST") as IDictionary<string, string>;
            if (list != null)
            {
                foreach (KeyValuePair<string, string> keyValue in list)
                {
                    if (userid.Equals(keyValue.Key.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        judgeexist = true;
                        break;
                    }
                }

                if (judgeexist)
                {
                    Response.Redirect("ForceLogout.aspx?UserID=" + userid);
                    return;
                }
            }
        }

        private bool JudgeOnline()
        {
            string userid = SessionBox.User.UserID;
            string sessionid = Session.SessionID;
            bool judgeexist = false;

            IDictionary<string, string> list = Application.Get("GLOBAL_USER_LIST") as IDictionary<string, string>;
            if (list != null)
            {
                foreach (KeyValuePair<string, string> keyValue in list)
                {
                    if (userid.Equals(keyValue.Key.Trim(), StringComparison.OrdinalIgnoreCase) && sessionid.Equals(keyValue.Value.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        judgeexist = true;
                        break;
                    }
                }
                return judgeexist;
            }
            else
            {
                return false;
            }
            
        }

    }
}